// 加载处理库
import XLSX from 'xlsx'
import { emit } from '../../services/socketio'

export const reset_tags = (state, dispatch) => {
    let tags = {}
    state.keys.forEach(key => {
        tags[key] = []
    })
    let file_data_cols = state.file_cols.map(i => i.title)

    dispatch({
        type: 'global/save',
        payload: {
            tag_bind: tags,
            file_data_cols: file_data_cols,
            format_file_data: []
        }
    })
}

export const upload_onChange = (info, state, dispatch) => {
    reset_tags(state, dispatch)

    dispatch({
        type: 'global/save',
        payload: {
            upload_file: info.file.name,
            file_cols: [],
            file_data: [],
            file_data_cols: [],
            format_file_data: [],
            sheet: '',
        }
    })
}

// 读取xlxs文件转json
export const xlsx_to_json = (jsonArr) => {
    // 获取表头信息
    let cols = jsonArr[0]
    let file_cols = cols.map(col => {
        col = col ? col : '-'
        return {
            title: col,
            dataIndex: col,
            key: col
        }
    })
    // 去除空值
    file_cols = file_cols.filter(f => f)

    // 获取数据
    let data = jsonArr.slice(1)
    data = data.filter(f => f.length !== 0)
    console.log(data)
    let file_data = data.map((it, id) => {
        let tmp = { key: id }
        cols.forEach((col, cid) => {
            tmp[col] = it[cid]
        })
        return tmp
    })
    let file_data_cols = cols

    return { file_cols, file_data, file_data_cols }
}

export const open_file = (file, dispatch) => {
    var reader = new FileReader();
    reader.onload = file => {
        console.log(file.name)
        // 读入工作表
        var workbook = XLSX.read(file.target.result, { type: 'binary' })
        dispatch({
            type: 'global/save',
            payload: { workbook: workbook, sheet_names: workbook.SheetNames }
        })
    }
    // 读取文件
    reader.readAsBinaryString(file)
    return false;
}

export const get_sheet_names = (state) => {
    return
}

// 读取本地XLSX文件函数
export const reader_file = (file, dispatch) => {

    var reader = new FileReader();
    reader.onload = file => {
        // 读入工作表
        var workbook = XLSX.read(file.target.result, { type: 'binary' })
        // 读入第一个sheet
        var first_worksheet = workbook.Sheets[workbook.SheetNames[0]];
        var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });

        dispatch({
            type: 'global/save',
            payload: { ...xlsx_to_json(jsonArr) }
        })
    }
    // 读取文件
    reader.readAsBinaryString(file)
    return false;
}

export const open_sheet = (sheet, state, dispatch) => {
    var first_worksheet = state.workbook.Sheets[sheet];
    var jsonArr = XLSX.utils.sheet_to_json(first_worksheet, { header: 1 });

    dispatch({
        type: 'global/save',
        payload: {
            ...xlsx_to_json(jsonArr),
            sheet: sheet,
            format_file_data: []
        }
    })
}

// 设置classname函数
export const setClassName = (target, str, value) => {
    if (target.className.search(str) !== -1) {
        target.className = value
    } else {
        target.parentNode.className = value
    }
}


// 公共拖动函数
export const drop = (e, m, dispatch, state) => {

    // 判断classname
    const ifClassName = (target, str) => {
        if (target.className.search(str) !== -1 || target.parentNode.className.search(str) !== -1) {
            return true
        } else {
            return false
        }
    }

    // 获取ClassName
    const getClassName = (target, str, re) => {
        if (re) {
            return target.id.search(str) === -1 ? target.parentNode.id : target.id
        } else {
            return target.id.search(str) !== -1 ? target.parentNode.id : target.id
        }

    }

    // 判断是否原位移动
    const ifLocal = (target, so, str, re) => {
        let p1 = getClassName(target, str, re)
        let p3 = document.getElementById(so).parentNode.className
        console.log(p1, 1, p3, 2, so)
        return p1 === p3 ? true : false
    }

    let so = e.dataTransfer.getData("Text")

    const dr = () => {
        console.log('dr-------------------')
        // 判断是否拖到系统标题
        if (ifClassName(e.target, 'table_drop_box')) {
            console.log('拖到系统标题')
            if (!ifLocal(e.target, so, 'table_drop_box')) {
                console.log('不是原位移动')

                let parentNode = document.getElementById(so).parentNode
                let key = getClassName(e.target, 'table_drop_box')

                if (parentNode.className === e.target.className) {
                    // 系统表头移动项目
                    let tmp = Object.assign({}, state.tag_bind)
                    tmp[key] = [...tmp[key], so]

                    dispatch({
                        type: 'global/save', payload: {
                            tag_bind: {
                                ...state.tag_bind,
                                [key]: tmp[key],
                                [parentNode.id]: tmp[parentNode.id].filter(i => i != so)
                            }
                        }
                    })

                } else {
                    // 从文件拖过来

                    let tmp = [...state.tag_bind[key]]
                    tmp.push(so)

                    let tmp2 = state.file_data_cols.filter(i => i !== so)

                    dispatch({
                        type: 'global/save', payload: {
                            tag_bind: { ...state.tag_bind, [key]: tmp }
                        }
                    })
                    dispatch({ type: 'global/save', payload: { file_data_cols: tmp2 } })
                }

            }
        }

        // 判断是否拖到文件标题
        if (ifClassName(e.target, 'file_tags')) {
            console.log('拖到文件标题')
            if (!ifLocal(e.target, so, 'file_tags', true)) {
                console.log('不是原位移动')

                let key = document.getElementById(so).parentNode.id
                let tmp = state.tag_bind[key].filter(i => i !== so)

                let tmp2 = [...state.file_data_cols]
                tmp2.push(so)

                dispatch({
                    type: 'global/save', payload: {
                        tag_bind: { ...state.tag_bind, [key]: tmp }
                    }
                })
                dispatch({ type: 'global/save', payload: { file_data_cols: tmp2 } })

            }
        }
    }
    // 判断是哪个元素接受拖入
    let target
    if (e.target.className.search('table') !== -1) {
        if (e.target.id) {
            target = e.target
        } else {
            target = e.target.parentNode
        }
    } else {
        if (e.target.id) {
            target = e.target.parentNode
        } else {
            target = e.target
        }
    }
    if (target.children.length < m) dr()
}

export const save_tags = (state, dispatch) => {
    console.log('save')
    let list = []
    state.file_data.forEach((row, rid) => {
        let str = {}
        for (const key in state.tag_bind) {
            str[key] = state.tag_bind[key].length > 1 ? state.tag_bind[key].map(k => row[k]) : row[state.tag_bind[key][0]] ? row[state.tag_bind[key][0]] : ''
        }
        list.push(str)
    })
    console.log(list)
    dispatch({ type: 'global/save', payload: { format_file_data: list } })
}


export const save_list_to_service = (state, dispatch) => {
    console.log("save_list_to_service")
    emit({ type: 'save_list', data: state.format_file_data })
}
